﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Prisa.BussinesLogic;
using Prisa.Entities;
using Microsoft.Practices.Unity;

namespace Prisa.UI
{
    public partial class frmVenta : Form
    {
        [Dependency]
        public IDetalleVentaBL detalleventaBL { get; set; }   

        [Dependency]
        public IVentaBL ventaBL { get; set; }

        [Dependency]
        public IProductoBL productoBL { get; set; }

        [Dependency]
        public ICategoriaBL categoriaBL { get; set; }

        public frmVenta()
        {
            InitializeComponent();
            this.BuildUp();
        }

        float f_HeightRatio = new float();
        float f_WidthRatio = new float();

        public void ResizeForm(Form ObjForm, int DesignerHeight, int DesignerWidth)
        {
            #region Code for Resizing and Font Change According to Resolution

            int i_StandardHeight = DesignerHeight;
            int i_StandardWidth = DesignerWidth;
            int i_PresentHeight = Screen.PrimaryScreen.Bounds.Height - 65;
            int i_PresentWidth = Screen.PrimaryScreen.Bounds.Width  - 245;
            f_HeightRatio = (float)((float)i_PresentHeight / (float)i_StandardHeight);
            f_WidthRatio = (float)((float)i_PresentWidth / (float)i_StandardWidth);
            //ObjForm.AutoScaleMode = AutoScaleMode.None;
            ObjForm.AutoScaleMode = AutoScaleMode.Dpi;
            ObjForm.Scale(new SizeF(f_WidthRatio, f_HeightRatio));
            foreach (Control c in ObjForm.Controls)
            {
                if (c.HasChildren)
                {
                    ResizeControlStore(c);
                }
                else
                {
                    c.Font = new Font(c.Font.FontFamily, c.Font.Size * f_HeightRatio, c.Font.Style, c.Font.Unit, ((byte)(0)));
                }
            }
            ObjForm.Font = new Font(ObjForm.Font.FontFamily, ObjForm.Font.Size * f_HeightRatio, ObjForm.Font.Style, ObjForm.Font.Unit, ((byte)(0)));
            #endregion
        }

        private void ResizeControlStore(Control objCtl)
        {
            #region

            if (objCtl.HasChildren)
            {
                foreach (Control cChildren in objCtl.Controls)
                {
                    if (cChildren.HasChildren)
                    {
                        ResizeControlStore(cChildren);
                    }
                    else
                    {
                        cChildren.Font = new Font(cChildren.Font.FontFamily, cChildren.Font.Size * f_HeightRatio, cChildren.Font.Style, cChildren.Font.Unit, ((byte)(0)));
                    }
                }
                objCtl.Font = new Font(objCtl.Font.FontFamily, objCtl.Font.Size * f_HeightRatio, objCtl.Font.Style, objCtl.Font.Unit, ((byte)(0)));
            }
            else
            {
                objCtl.Font = new Font(objCtl.Font.FontFamily, objCtl.Font.Size * f_HeightRatio, objCtl.Font.Style, objCtl.Font.Unit, ((byte)(0)));
            }
            #endregion
        }
       
        private void frmVenta_Load(object sender, EventArgs e)
        {
            //this.ResizeForm(this, 700, 1036); 
            dateTimePicker1.Enabled = false;
            dateTimePicker2.Enabled = false;

            ReiniciarFechas();

            LoadVentas();
        }

        private void ReiniciarFechas()
        {
            dateTimePicker1.Value = DateTime.Now.Date;
            var fec2 = dateTimePicker1.Value.Date;
            dateTimePicker2.Value = fec2.AddDays(1);
        }

        private void LoadVentas()
        {
            vENTABindingSource.DataSource = ventaBL.GetAllFromVentas();
            var venta = vENTABindingSource.Current as VENTA;
            if (venta != null)
            {
                dETALLEVENTAsBindingSource.DataSource = ventaBL.GetFromVentaById(venta.Id);
            }
        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            BuscarBoletas();
            BuscarFacturas();
            BuscarEnTodos();
        }

        private void txtCliente_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BuscarBoletas();
                BuscarFacturas();
                BuscarEnTodos();
            }
        }

        private void vENTADataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            var _venta = vENTABindingSource.Current as VENTA;
            if (_venta != null)
            {
                dETALLEVENTAsBindingSource.DataSource = detalleventaBL.GetFromDetalleVentaByProductoDescAndVentaId("", _venta.Id);

                var _total = Math.Round(_venta.Total, 2);
                LTotal.Text = _total.ToString();
            }
            else LTotal.Text = "0.00";
        }

        private void vENTADataGridView_CurrentCellChanged(object sender, EventArgs e)
        {
            var _venta = vENTABindingSource.Current as VENTA;
            if (_venta != null)
            {
                dETALLEVENTAsBindingSource.DataSource = ventaBL.GetFromVentaById(_venta.Id);
                var _total = Math.Round(_venta.Total, 2);
                LTotal.Text = _total.ToString();
                dETALLEVENTAsBindingSource.DataSource = detalleventaBL.GetFromDetalleVentaByProductoDescAndVentaId("", _venta.Id);
            }
            else
            {
                LTotal.Text = "0.00";
                dETALLEVENTAsBindingSource.Clear();
            }
        }

        private void TxtProductoDesc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BuscarEnDetalleVenta();
            }
        }

        private void BtnBuscarProducto_Click(object sender, EventArgs e)
        {
            BuscarEnDetalleVenta();
        }

        private void BuscarEnDetalleVenta()
        {
            VENTA currentVenta = vENTABindingSource.Current as VENTA;
            if (currentVenta != null)
            {
                dETALLEVENTAsBindingSource.DataSource = detalleventaBL.GetFromDetalleVentaByProductoDescAndVentaId(TxtProductoDesc.Text, currentVenta.Id);
            }
            else
            {
                MessageBox.Show("Debe seleccionar una Venta", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void rbtnGeneral_CheckedChanged(object sender, EventArgs e)
        {
            BuscarEnTodos();
        }

        private void BuscarEnTodos()
        {
            if (rbtnGeneral.Checked == true && rbtnClienteyFecha.Checked == true)
            {
                dateTimePicker1.Enabled = true;
                dateTimePicker2.Enabled = true;
                lblFec2.Visible = true;
                dateTimePicker2.Visible = true;
                lblFec1.Text = "Desde:";
                var fec1 = dateTimePicker1.Value.Date;
                var fec2 = dateTimePicker2.Value.Date;
                if (fec1 <= fec2)
                {
                    vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndCliente(fec1, fec2, txtCliente.Text);
                }
                else
                {
                    ReiniciarFechas();
                    MessageBox.Show("La fecha de inicio debe ser menor o igual a la fecha de término", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            if (rbtnGeneral.Checked == true && rbtnCliente.Checked == true)
            {
                dateTimePicker1.Enabled = false;
                dateTimePicker2.Enabled = false;
                lblFec2.Visible = true;
                dateTimePicker2.Visible = true;
                lblFec1.Text = "Desde:";
                vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndCliente(null, null, txtCliente.Text);
            }
            if (rbtnGeneral.Checked == true && rbtnFecha.Checked == true)
            {
                dateTimePicker1.Enabled = true;
                dateTimePicker2.Enabled = true;
                lblFec2.Visible = true;
                dateTimePicker2.Visible = true;
                lblFec1.Text = "Desde:";
                var fec1 = dateTimePicker1.Value.Date;
                var fec2 = dateTimePicker2.Value.Date;
                if (fec1 <= fec2)
                {
                    vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndCliente(fec1, fec2, "");
                }
                else
                {
                    ReiniciarFechas();
                    MessageBox.Show("La fecha de inicio debe ser menor o igual a la fecha de término", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            if (rbtnGeneral.Checked == true && rbtnDia.Checked == true)
            {
                dateTimePicker1.Enabled = true;
                dateTimePicker2.Enabled = true;
                var fec1 = dateTimePicker1.Value.Date;
                lblFec2.Visible = false;
                dateTimePicker2.Visible = false;
                lblFec1.Text = "Día:";
                vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndCliente(fec1, null, txtCliente.Text);
            }
            var _currentVenta = vENTABindingSource.Current as VENTA;
            {
                if (_currentVenta != null)
                {
                    dETALLEVENTAsBindingSource.DataSource = detalleventaBL.GetFromDetalleVentaByProductoDescAndVentaId("", _currentVenta.Id);
                }
                else
                {
                    dETALLEVENTAsBindingSource.Clear();
                }
            }
        }

        private void BuscarBoletas()
        {
            if (rbtnBoletas.Checked == true && rbtnClienteyFecha.Checked == true)
            {
                dateTimePicker1.Enabled = true;
                dateTimePicker2.Enabled = true;
                lblFec2.Visible = true;
                dateTimePicker2.Visible = true;
                lblFec1.Text = "Desde:";
                var fec1 = dateTimePicker1.Value.Date;
                var fec2 = dateTimePicker2.Value.Date;

                vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndClienteAndBoleta(fec1, fec2, txtCliente.Text);
            }
            if (rbtnBoletas.Checked == true && rbtnCliente.Checked == true)
            {
                dateTimePicker1.Enabled = false;
                dateTimePicker2.Enabled = false;
                lblFec2.Visible = true;
                dateTimePicker2.Visible = true;
                lblFec1.Text = "Desde:";
                vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndClienteAndBoleta(null, null, txtCliente.Text);
            }
            if (rbtnBoletas.Checked == true && rbtnFecha.Checked == true)
            {
                dateTimePicker1.Enabled = true;
                dateTimePicker2.Enabled = true;
                lblFec2.Visible = true;
                dateTimePicker2.Visible = true;
                lblFec1.Text = "Desde:";
                var fec1 = dateTimePicker1.Value.Date;
                var fec2 = dateTimePicker2.Value.Date;
                if (fec1 <= fec2)
                {
                    vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndClienteAndBoleta(fec1, fec2, "");
                }
                else
                {
                    ReiniciarFechas();
                    MessageBox.Show("La fecha de inicio debe ser menor o igual a la fecha de término", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            if (rbtnBoletas.Checked == true && rbtnDia.Checked == true)
            {
                dateTimePicker1.Enabled = true;
                dateTimePicker2.Enabled = true;
                var fec1 = dateTimePicker1.Value.Date;
                lblFec2.Visible = false;
                dateTimePicker2.Visible = false;
                lblFec1.Text = "Día:";
                vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndClienteAndBoleta(fec1, null, txtCliente.Text);
            }
            var _currentVenta = vENTABindingSource.Current as VENTA;
            {
                if (_currentVenta != null)
                {
                    dETALLEVENTAsBindingSource.DataSource = detalleventaBL.GetFromDetalleVentaByProductoDescAndVentaId("", _currentVenta.Id);
                }
                else
                {
                    dETALLEVENTAsBindingSource.Clear();
                }
            }
        }

        private void BuscarFacturas()
        { 
            if (rbtnFacturas.Checked == true && rbtnClienteyFecha.Checked == true)
            {
                dateTimePicker1.Enabled = true;
                dateTimePicker2.Enabled = true;
                lblFec2.Visible = true;
                dateTimePicker2.Visible = true;
                lblFec1.Text = "Desde:";
                var factura = rbtnFacturas.Checked;
                var fec1 = dateTimePicker1.Value.Date;
                var fec2 = dateTimePicker2.Value.Date;
                if (fec1 <= fec2)
                {
                    vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndClienteAndFactura(fec1, fec2, txtCliente.Text, factura);
                }
                else
                {
                    ReiniciarFechas();
                    MessageBox.Show("La fecha de inicio debe ser menor o igual a la fecha de término", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            if (rbtnFacturas.Checked == true && rbtnCliente.Checked == true)
            {
                dateTimePicker1.Enabled = false;
                dateTimePicker2.Enabled = false;
                lblFec2.Visible = true;
                dateTimePicker2.Visible = true;
                lblFec1.Text = "Desde:";
                var factura = rbtnFacturas.Checked;
                vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndClienteAndFactura(null, null, txtCliente.Text, factura);
            }
            if (rbtnFacturas.Checked == true && rbtnFecha.Checked == true)
            {
                dateTimePicker1.Enabled = true;
                dateTimePicker2.Enabled = true;
                lblFec2.Visible = true;
                dateTimePicker2.Visible = true;
                lblFec1.Text = "Desde:";
                var factura = rbtnFacturas.Checked;
                var fec1 = dateTimePicker1.Value.Date;
                var fec2 = dateTimePicker2.Value.Date;
                if (fec1 <= fec2)
                {
                    vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndClienteAndFactura(fec1, fec2, "", factura);
                }
                else
                {
                    ReiniciarFechas();
                    MessageBox.Show("La fecha de inicio debe ser menor o igual a la fecha de término", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            if (rbtnFacturas.Checked == true && rbtnDia.Checked == true)
            {
                dateTimePicker1.Enabled = true;
                dateTimePicker2.Enabled = true;
                var fec1 = dateTimePicker1.Value.Date;
                lblFec2.Visible = false;
                dateTimePicker2.Visible = false;
                lblFec1.Text = "Día:";
                var factura = rbtnFacturas.Checked;
                vENTABindingSource.DataSource = ventaBL.GetFromVentasbyFechaAndClienteAndFactura(fec1, null, txtCliente.Text, factura);
            }
            var _currentVenta = vENTABindingSource.Current as VENTA;
            {
                if (_currentVenta != null)
                {
                    dETALLEVENTAsBindingSource.DataSource = detalleventaBL.GetFromDetalleVentaByProductoDescAndVentaId("", _currentVenta.Id);
                }
                else
                {
                    dETALLEVENTAsBindingSource.Clear();
                }
            }
        }

        private void rbtnBoletas_CheckedChanged(object sender, EventArgs e)
        {
            BuscarBoletas();
        }

        private void rbtnFacturas_CheckedChanged(object sender, EventArgs e)
        {
            BuscarFacturas();
        }

        private void rbtnCliente_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnCliente.Checked == true)
            {
                txtCliente.ReadOnly = false;
            }
        }

        private void rbtnFecha_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnFecha.Checked == true)
            {
                txtCliente.ReadOnly = true;
            }
        }

        private void rbtnClienteyFecha_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnClienteyFecha.Checked == true)
            {
                txtCliente.ReadOnly = false;
            }
        }

        private void rbtnGeneral_Click(object sender, EventArgs e)
        {
            BuscarEnTodos();
        }

        private void rbtnBoletas_Click(object sender, EventArgs e)
        {
            BuscarBoletas();
        }

        private void rbtnFacturas_Click(object sender, EventArgs e)
        {
            BuscarFacturas();
        }

        private void rbtnCliente_Click(object sender, EventArgs e)
        {
            BuscarBoletas();
            BuscarEnTodos();
            BuscarFacturas();
            if (rbtnCliente.Checked == true)
            {
                txtCliente.ReadOnly = false;
            }
        }

        private void rbtnFecha_Click(object sender, EventArgs e)
        {
            if (rbtnFecha.Checked == true)
            {
                txtCliente.ReadOnly = true;
            }
            BuscarBoletas();
            BuscarEnTodos();
            BuscarFacturas();
        }

        private void rbtnClienteyFecha_Click(object sender, EventArgs e)
        {
            BuscarBoletas();
            BuscarEnTodos();
            BuscarFacturas();
            if (rbtnClienteyFecha.Checked == true)
            {
                txtCliente.ReadOnly = false;
            }
        }

        private void rbtnDia_CheckedChanged(object sender, EventArgs e)
        {
            txtCliente.ReadOnly = true;
        }

        private void rbtnDia_Click(object sender, EventArgs e)
        {
            BuscarBoletas();
            BuscarEnTodos();
            BuscarFacturas();
            if (rbtnDia.Checked == true)
            {
                txtCliente.ReadOnly = false;
            }
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            frmMttoVenta frm = new frmMttoVenta();
            frm.Nuevo();
            frm.ShowDialog();
            LoadVentas();
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            var _venta = vENTABindingSource.Current as VENTA;

            if (_venta != null)
            {
                if (_venta.Cancelada == false)
                {
                    var rpt = MessageBox.Show(this, string.Format("Desea cancelar la venta?"), "Mensaje", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (rpt == DialogResult.Yes)
                    {
                        if (txtObservacion.Text.Length != 0)
                        {
                            _venta.Observacion = txtObservacion.Text;
                            _venta.Cancelada = true;
                            ventaBL.CancelarVenta(_venta.Id);
                            foreach (var item in _venta.DETALLEVENTAs)
                            {
                                var producto = productoBL.GetFromProductoById(item.ProductoId);
                                var categoria = categoriaBL.GetFromCategoriaById(producto.CategoriaId);
                                var actproducto = producto;
                                actproducto.CATEGORIA = categoria;
                                actproducto.Stock = producto.Stock + item.Cantidad;
                                productoBL.UpdateProducto(actproducto);
                            }
                            vENTABindingSource.DataSource = ventaBL.GetAllFromVentas();
                            MessageBox.Show("Venta cancelada correctamente", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            txtObservacion.Text = "";
                            LoadVentas();
                        }
                        else
                        {
                            MessageBox.Show(this, string.Format("Es necesario ingresar una observación"), "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            txtObservacion.Focus();
                        }
                    }
                    dETALLEVENTAsBindingSource.DataSource = detalleventaBL.GetFromDetalleVentaByProductoDescAndVentaId("", _venta.Id);
                }
                else MessageBox.Show("Esta venta ya está cancelada", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Debe seleccionar una venta", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                dETALLEVENTAsBindingSource.Clear();
            }                    

        }

        private void txtCliente_KeyPress(object sender, KeyPressEventArgs e)
        {
            var guion = Convert.ToString("-");
            var coma = Convert.ToString(",");
            var punto = Convert.ToString(".");
            var slash = Convert.ToString("/");
            string cadena = guion + coma + punto + slash + (char)8;
            if (!cadena.Contains(e.KeyChar) && !(char.IsLetter(e.KeyChar)) && !(char.IsNumber(e.KeyChar))
                && (e.KeyChar != (char)Keys.Back) && (e.KeyChar != (char)Keys.Enter) && (e.KeyChar != (char)Keys.Clear)
                && !(char.IsSeparator(e.KeyChar)))
            {
                e.Handled = true;
                return;
            }
        }

        private void TxtProductoDesc_KeyPress(object sender, KeyPressEventArgs e)
        {
            var guion = Convert.ToString("-");
            var coma = Convert.ToString(",");
            var punto = Convert.ToString(".");
            var slash = Convert.ToString("/");
            var amber = Convert.ToString("&");

            string cadena = guion + coma + punto + slash + amber + (char)8;
            if (!cadena.Contains(e.KeyChar) && !(char.IsLetter(e.KeyChar)) && !(char.IsNumber(e.KeyChar))
                && (e.KeyChar != (char)Keys.Back) && (e.KeyChar != (char)Keys.Enter) && (e.KeyChar != (char)Keys.Clear)
                && !(char.IsSeparator(e.KeyChar)))
            {
                e.Handled = true;
                return;
            }
        }

    }
}
